<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {
	
		
	function __construct()
    {
        // Call the Controller constructor
        parent::__construct();
		$this->load->model('user_model');
		$this->load->library('facebook');
		//$this->facebook = new Facebook();
    }
	
	function index(){
				
		$user = $this->facebook->getUser();

		// We may or may not have this data based on whether the user is logged in.
		//
		// If we have a $user id here, it means we know the user is logged into
		// Facebook, but we don't know if the access token is valid. An access
		// token is invalid if the user logged out of Facebook.

		if ($user) {
		  try {
			// Proceed knowing you have a logged in user who's authenticated.
			$user_profile = $this->facebook->api('/me');
		  } catch (FacebookApiException $e) {
			error_log($e);
			$user = null;
		  }
		}
		
		// Login or logout url will be needed depending on current user state.
		if ($user) {
		  $logoutUrl = $this->facebook->getLogoutUrl();
		  $loginUrl = '';
		} else {
		  $loginUrl = $this->facebook->getLoginUrl();
		  $logoutUrl = '';
		}
		
		$userdb = $this->user_model->get_user($user);
		
		if ($userdb->num_rows() > 0) {
			
			$userdata = $this->user_model->get_user($user);
			$data['uid'] = $userdata->row()->id_user;
			$data['alamat'] = $userdata->row()->Alamat;			
			$data['user_profile'] = $user_profile;
			
			
		}
		else if($user){
			$location = $user_profile['location'];
			$data = array(
						'id_user' => $user_profile['id'],
						'alamat' => $location['name'],
						//'Email' => $user_profile['email'],
						'Nama' => $user_profile['name'],
						'id_role_user' => '2'
					);
			
			$this->user_model->add($data);
			$userdata = $this->user_model->get_user($user);
			$data['uid'] = $userdata->row()->id_user;
			$data['alamat'] = $userdata->row()->Alamat;
			$data['user_profile'] = $user_profile;
			
		}
		
		
		$data['user'] = $user;
		$data['logoutUrl'] = $logoutUrl;
		$data['loginUrl'] = $loginUrl;
		
		$this->load->view('welcome_message', $data);
	}

}
